package com.example.demo.controller;

import com.example.demo.common.RestResult;
import com.example.demo.model.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

// 允许跨域请求，允许所有来源，缓存时间为3600秒
@CrossOrigin(origins = "*", maxAge = 3600)
// 当前类作为REST控制器，处理HTTP请求
@RestController
// 所有接口的请求路径前缀为 /api/users
@RequestMapping("/api/users")
public class UserController {
    // 自动注入UserService服务类
    @Autowired
    private UserService userService;

    // 获取所有用户信息（分页+过滤），仅限ADMIN角色访问
    @GetMapping
    @PreAuthorize("hasRole('ADMIN')")
    public RestResult<org.springframework.data.domain.Page<User>> getAllUsers(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String email,
            @RequestParam(required = false) Boolean isActive) {
        org.springframework.data.domain.Pageable pageable = org.springframework.data.domain.PageRequest.of(page, size);
        org.springframework.data.domain.Page<User> usersPage = userService.getUsersByFilters(username, email, isActive, pageable);
        return RestResult.success(usersPage);
    }

    // 根据用户ID获取单个用户信息，USER或ADMIN角色可访问
    @GetMapping("/{id}")
    @PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
    public RestResult<User> getUserById(@PathVariable Long id) {
        // 获取当前登录用户的用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        System.out.println("当前用户角色: " + userDetails.getAuthorities());

        // 调用服务层根据ID查询用户，返回Optional<User>
        return userService.getUserById(id)
                // 如果用户存在，返回成功状态及用户信息
                .map(RestResult::success)
                // 如果用户不存在，返回错误状态
                .orElse(RestResult.error("用户不存在"));
    }

    // 编辑用户信息，仅限ADMIN角色访问
    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public RestResult<User> updateUser(@PathVariable Long id, @RequestBody User user) {
        // 设置用户ID，确保更新的是指定ID的用户
        user.setId(id);
        // 调用服务层方法更新用户信息
        User updatedUser = userService.updateUser(user);
        // 返回成功状态码及更新后的用户信息
        return RestResult.success(updatedUser);
    }

    // 启用/禁用用户，仅限ADMIN角色访问
    @PatchMapping("/{id}/status")
    @PreAuthorize("hasRole('ADMIN')")
    public RestResult<User> toggleUserStatus(@PathVariable Long id, @RequestParam Boolean isActive) {
        // 调用服务层方法切换用户状态
        User updatedUser = userService.toggleUserStatus(id, isActive);
        // 返回成功状态码及更新后的用户信息
        return RestResult.success(updatedUser);
    }

}
